package com.nbcio.modules.erp.export.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbcio.common.core.domain.R;
import com.nbcio.modules.erp.export.domain.ErpExportJob;
import com.nbcio.modules.erp.export.service.IErpExportJobService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Tag(name = "ERP导出任务")
@RestController
@RequestMapping("/erp/export/job")
@RequiredArgsConstructor
public class ErpExportJobController {

    private final IErpExportJobService jobService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping
    public R<Long> create(@RequestParam String module, @RequestBody Map<String, Object> params) throws Exception {
        Long userId = StpUtil.getLoginIdAsLong();
        String json = objectMapper.writeValueAsString(params);
        Long jobId = jobService.createJob(userId, module, json);
        jobService.runJobAsync(jobId);
        return R.ok(jobId);
    }

    @GetMapping("/{jobId}/status")
    public R<Map<String, Object>> status(@PathVariable Long jobId) {
        ErpExportJob job = jobService.getById(jobId);
        if (job == null) return R.fail("job not found");
        return R.ok(Map.of(
                "status", job.getStatus(),
                "progress", job.getProgress(),
                "errorMsg", job.getErrorMsg()
        ));
    }

    @GetMapping("/{jobId}/download")
    public ResponseEntity<FileSystemResource> download(@PathVariable Long jobId) throws Exception {
        ErpExportJob job = jobService.getById(jobId);
        if (job == null || job.getFilePath() == null) return ResponseEntity.notFound().build();
        File file = new File(job.getFilePath());
        if (!file.exists()) return ResponseEntity.notFound().build();
        String name = file.getName();
        String encoded = URLEncoder.encode(name, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encoded)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(file));
    }
}


